package ph.com.gs3.formalistics.presenter.fragments.workers;

import java.util.ArrayList;
import java.util.List;

import ph.com.gs3.formalistics.model.dao.CommentsDAO;
import ph.com.gs3.formalistics.model.dao.SQLiteDataAccessObject.DeleteFailedException;
import ph.com.gs3.formalistics.model.dao.SQLiteDataAccessObject.UpdateFailedException;
import ph.com.gs3.formalistics.model.valueobjects.business.Comment;
import ph.com.gs3.formalistics.view.valueobjects.parsers.DateUtilities;
import android.app.Fragment;
import android.content.Context;

public class CommentsWorkerFragment extends Fragment {

	public static final String TAG = CommentsWorkerFragment.class.getSimpleName();

	private CommentsDAO commentsDAO;

	public static CommentsWorkerFragment createInstance(Context applicationContext) {

		CommentsWorkerFragment instance = new CommentsWorkerFragment();

		instance.commentsDAO = new CommentsDAO(applicationContext);

		return instance;

	}

	public List<Comment> getDocumentComments(String server, String formId, String documentWebId) {

		List<Comment> comments = new ArrayList<>();

		commentsDAO.open();
		comments = commentsDAO.getDocumentComments(server, formId, documentWebId);
		commentsDAO.close();

		return comments;

	}

	public Comment saveCommentAsOutgoingComment(Comment comment) {

		String currentDate = DateUtilities.getServerFormattedCurrentDate();

		comment.setWebId("0");
		comment.setOutgoing(true);
		comment.setDateCreated(currentDate);

		commentsDAO.open();
		comment = commentsDAO.saveComment(comment);
		commentsDAO.close();

		return comment;

	}

	public void deleteComment(String commentDbId) throws CommentDeleteFailedException {

		commentsDAO.open();
		try {
			commentsDAO.deleteComment(commentDbId);
		} catch (DeleteFailedException e) {
			throw new CommentDeleteFailedException(e);
		} finally {
			commentsDAO.close();
		}

	}

	public Comment markCommentForDeletion(String commentDbId) throws CommentDeleteFailedException {

		commentsDAO.open();
		Comment markedComment;
		try {
			markedComment = commentsDAO.markCommentForDeletion(commentDbId);
			return markedComment;
		} catch (UpdateFailedException e) {
			throw new CommentDeleteFailedException(e);
		} finally {
			commentsDAO.close();
		}

	}

	public static class CommentDeleteFailedException extends Exception {

		private static final long serialVersionUID = 7137914299507523040L;

		public CommentDeleteFailedException(String message) {
			super(message);
		}

		public CommentDeleteFailedException(Throwable throwable) {
			super(throwable);
		}

		public CommentDeleteFailedException(String message, Throwable throwable) {
			super(message, throwable);
		}

	}

}
